from __future__ import print_function
import os
import telnetlib
import configparser
import logging
from time import sleep


class server_detail(object):  # 定义一个类people
    def _init_(self, server_name, ip, port):
        self.serverName = server_name
        self.IP = ip
        self.Port = port


def check_server_list(server_name):
    res = os.popen("sc query %s" % server_name)
    d = res.read()
    if "STOPPED" in d:
        return False
    else:
        return True


def check_port(host, port):
    try:
        t = telnetlib.Telnet(host, port=port, timeout=1)
        return True
    except:
        return False


def kill_server(server_name, port):
    os.system("net stop %s" % server_name)
    res = os.popen("netstat -ano |findstr %d" % port)
    if port != 0:
        d = res.read()
        strLst = d.split()
        if len(strLst) >= 4:
            os.system("taskkill -f -pid %s" % strLst[4])


def stat_server(server_name):
    os.system("net start %s" % server_name)


def read_config():
    server_lst = []
    config = configparser.ConfigParser()
    config.read("Config.ini")
    sections = config.sections()
    for section in sections:
        sd = server_detail()
        try:
            serverName = config.get(section, 'ServerName')
            IP = config.get(section, "IP")
            Port = config.getint(section, 'ListenPort')
        except:
            sd.serverName = serverName
            sd.IP = '127.0.0.1'
            sd.Port = 0
        else:
            sd.serverName = serverName
            sd.IP = IP
            sd.Port = Port
        server_lst.append(sd)
    return server_lst


def init():
    log_file = 'watch_dog.log'
    log_format = '%(asctime)s[%(levelname)s]: %(message)s'
    logging.basicConfig(filename=log_file, level=logging.WARNING, format=log_format)


if __name__ == '__main__':
    init()
    logging.error("看门狗启动中...")
    # 加载配置文件，获取服务列表
    server_lst = read_config()
    if len(server_lst) == 0:
        logging.error("需要守护的服务列表为空,程序即将推出")
    else:
        while 1:
            for item in server_lst:
                if check_server_list(item.serverName) == False:  # 需要守护的服务未启动状态
                    logging.error("[%s] need restat!" % item.serverName)
                    kill_server(item.serverName, item.Port)  # 先把端口占用过的进程干掉
                    stat_server(item.serverName)
                if item.Port == 0:
                    continue
                if check_port(item.IP, item.Port) == False:
                    logging.error("[%s] need restat!" % item.serverName)
                    kill_server(item.serverName, item.Port)  # 先把端口占用过的进程干掉
                    stat_server(item.serverName)
            sleep(2)
            print("看门狗守护中...")
